package com.dragon.speech.service;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.polly.AmazonPolly;
import com.amazonaws.services.polly.AmazonPollyClientBuilder;
import com.amazonaws.services.polly.model.*;
import com.amazonaws.util.IOUtils;
import com.dragon.utils.MD5Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * aws tts 从文字到语音
 * Created by jingcai.li on 2017/5/21.
 */
@Component
public class AwsPolly {
//    private static final String SAMPLE = "Congratulations. You have successfully built " +
//            "this working demo of Amazon Polly in Java. Have fun building voice enabled apps with " +
//            "Amazon Polly (that's me!), and always look at the AWS website for tips and tricks on" +
//            " using Amazon Polly and other great services from AWS";

    @Value("${audio_file_path}")
    private String AUDIO_FILE_PATH;

    public boolean getAudio(String text){
        String md5 = MD5Util.code(text);
        String audioPath = AUDIO_FILE_PATH+"/"+md5+".mp3";
        File file  = new File(audioPath);
        //如果已经存在直接返回
        if(file.exists()){
            return  true;
        }
        boolean result = true;
        try {
            this.synthesize(text,audioPath);
        }catch (IOException ie){
            file = new File(audioPath);
            if(file.exists()&&file.isFile()){
                file.delete();
            }
            result = false;
        }
        return result;
    }

    private void synthesize(String text,String audioPath) throws IOException {
        AmazonPolly polly;
        Voice voice;
        text = "<speak><prosody rate=\"x-slow\">"+text+"</prosody></speak>";
        BasicAWSCredentials awsCreds = new BasicAWSCredentials("AKIAJDBKXCEF5HOKKKSA", "As3bvirSM2dvl50mb8hdzY7GJ+7XpaVdJRXVF8ES");
        polly = AmazonPollyClientBuilder.standard().withRegion(Regions.EU_WEST_1)
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .build();
        // Create describe voices request.
        DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
        describeVoicesRequest.setLanguageCode(LanguageCode.EnUS);
        // Synchronously ask Amazon Polly to describe available TTS voices.
        DescribeVoicesResult describeVoicesResult =
                polly.describeVoices(describeVoicesRequest);
        voice = describeVoicesResult.getVoices().get(0);
        SynthesizeSpeechRequest synthReq =
                new SynthesizeSpeechRequest().withTextType("ssml").withText(text).withVoiceId(voice.getId())
                        .withOutputFormat(OutputFormat.Mp3);
        SynthesizeSpeechResult synthRes = polly.synthesizeSpeech(synthReq);
        IOUtils.copy(synthRes.getAudioStream(),new FileOutputStream(audioPath));
    }

}
